package com.vic.kjlink.order.service;

import java.math.BigInteger;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.vic.kjlink.order.controller.BaseOrderController;
import com.vic.kjlink.order.model.User;
import com.vic.kjlink.order.third.OaLoginUtil;

import pers.vic.boot.base.model.BaseResponse;
import pers.vic.boot.util.CookieUtil;
import pers.vic.boot.util.JsonUtil;

/**
 * @author Vic.xu
 * @description:
 * @date: 2021/8/20 0020 10:54
 */
@Service
public class IndexService {

    @Resource
    private UserService userService;

    /**
     * 登录校验 并存入到Cookie
     * 
     * @param userCode
     * @param password
     * @return
     */
    public BaseResponse<User> login(String userCode, String password) {
        User user = userService.getByUserCode(userCode);
        if (user == null) {
            user = OaLoginUtil.login(userCode, password);
            if (user == null) {
                return BaseResponse.error("工号或密码错误");
            }
            // 新增到本地
            user.setPassword(password);
            userService.insert(user);
            return BaseResponse.success(user);
        }
        if (!StringUtils.equals(password, user.getPassword())) {
            return BaseResponse.error("工号或密码错误");
        }
        return BaseResponse.success(user);
    }

    /**
     * 根据cookie判断当前是否已经登录
     * 
     * @param request
     * @return
     */
    public User ifLogin(HttpServletRequest request) {
        String cookieToken = CookieUtil.getValue(request, BaseOrderController.PRINCIPAL);
        if (cookieToken != null) {
            User cookieUser = parseToken(cookieToken);
            if (cookieUser != null) {
                User dbUser = userService.getByUserCode(cookieUser.getUserCode());
                if (dbUser != null) {
                    if (cookieUser.getPassword().equals(dbUser.getPassword())) {
                        return dbUser;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 把user转为token
     * 
     * @param user
     * @return
     */
    public String makeToken(User user) {
        String tokenJson = JsonUtil.toJson(user);
        String tokenHex = new BigInteger(tokenJson.getBytes()).toString(16);
        return tokenHex;
    }

    /**
     * 把token转为user
     * 
     * @param tokenHex
     * @return
     */
    public User parseToken(String tokenHex) {
        User user = null;
        if (tokenHex != null) {
            String tokenJson = new String(new BigInteger(tokenHex, 16).toByteArray()); // username_password(md5)
            user = JsonUtil.jsonToObject(tokenJson, User.class);
        }
        return user;
    }

}
